package sanglh.edu.hsphysics.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import sanglh.edu.hsphysics.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.support.v4.content.IntentCompat;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

public class FileUtil {
	private static final String DISK_CACHE_SUBDIR = "thumbnails";
	private static final String DISK_TEMP_SUBDIR = "temps";
	public static final String DISK_OFFLINE_GOOGLEDRIVE_SUBDIR = "drive";

	// public static final String EXTERNAL = "EXTERNAL";
	// public static final String INTERNAL = "INTERNAL";

	public static void openFile(Context context, File file) {
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
		intent.setFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
		intent.setDataAndType(Uri.fromFile(file),
				getMimeType(file.getAbsolutePath()));
		try {
			context.startActivity(intent);
		} catch (Exception e) {
			FileUtil.delete(file);
		}
	}
	
	public static void openFile(Activity activity, File file, int requestCode) {
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
		intent.setFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
		intent.setDataAndType(Uri.fromFile(file),
				getMimeType(file.getAbsolutePath()));
		try {
			activity.startActivityForResult(intent, requestCode);
		} catch (Exception e) {
			FileUtil.delete(file);
		}
	}

	public static String getMimeType(String path) {
		MimeTypeMap map = MimeTypeMap.getSingleton();
		String ext = "*/*";
		try {
			if (!path.contains(".")) {
				return ext;
			}
			ext = path.substring(path.lastIndexOf(".") + 1);
			String type = map.getMimeTypeFromExtension(ext.toLowerCase());
			return TextUtils.isEmpty(type) ? "*/*" : type;
		} catch (Exception e) {
			return ext;
		}

	}

	// public static String getMimeTypeFromExtension(String ext) {
	// MimeTypeMap map = MimeTypeMap.getSingleton();
	// try {
	// String type = map.getMimeTypeFromExtension(ext.toLowerCase());
	// return TextUtils.isEmpty(type) ? "*/*" : type;
	// } catch (Exception e) {
	// return ext;
	// }
	//
	// }

	public static String getExt(String path) {
		String ext = "";
		try {
			ext = path.substring(path.lastIndexOf("."));
		} catch (Exception e) {
		}
		return ext;

	}

	public static String getNameWithoutExt(String name) {
		try {
			return name.substring(0, name.lastIndexOf("."));
		} catch (Throwable e) {
		}
		return name;

	}

	public static void deleteInternalCacheDir(Context context) {
		File cacheFile = getInternalCacheDirectory(context);
		File[] files = cacheFile.listFiles();
		if (files == null) {
			return;
		}

		for (File file : files) {
			if (file.isFile()) {
				file.delete();
			} else {
				deleteInternalCacheDir(context);
			}
		}
	}

	public static void deleteTempDir(Context context) {
		File cacheFile = getTempDirectory(context);
		File[] files = cacheFile.listFiles();
		if (files == null) {
			return;
		}

		for (File file : files) {
			if (file.isFile()) {
				file.delete();
			} else {
				deleteTempDir(context);
			}
		}
	}

	// public static void deleteSharingDir(Context context) {
	// File cacheFile = getSharingDirectory(context);
	// File[] files = cacheFile.listFiles();
	// if (files == null) {
	// return;
	// }
	//
	// for (File file : files) {
	// if (file.isFile()) {
	// file.delete();
	// } else {
	// getSharingDirectory(context);
	// }
	// }
	// }

	public static InputStream getInputStream(final Context context,
			final Uri uri) {
		InputStream inputStream = null;
		// MediaStore (and general)
		if ("content".equalsIgnoreCase(uri.getScheme())) {
			try {
				return context.getContentResolver().openInputStream(uri);
			} catch (FileNotFoundException e) {
				Logging.print(e);
			}
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			try {
				File file = new File(uri.getPath());
				return new FileInputStream(file);
			} catch (FileNotFoundException e) {
				Logging.print(e);
			}
		}

		return inputStream;
	}

	public static String getFileName(Context context, Uri uri) {
		if (uri == null) {
			return "";
		}
		// MediaStore (and general)
		if ("content".equalsIgnoreCase(uri.getScheme())) {
			Cursor returnCursor = context.getContentResolver().query(uri, null,
					null, null, null);
			if (null != returnCursor) {
				int nameIndex = returnCursor
						.getColumnIndex(OpenableColumns.DISPLAY_NAME);
				returnCursor.moveToFirst();
				String name = returnCursor.getString(nameIndex);
				String segment = uri.getLastPathSegment();
				if (segment.startsWith("http")) {
					String last = segment.substring(segment
							.lastIndexOf(File.separator) + 1);
					return last;
				}
				returnCursor.close();
				return name;
			}
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return (new File(uri.getPath())).getName();
		}
		return createTimeStamp();

	}

	// public static File getCacheDirectory(Context context) {
	// // Check if media is mounted or storage is built-in, if so, try and use
	// // external cache dir
	// // otherwise use internal cache dir
	// final String cachePath = DeviceUtil.hasSDCard() ? context
	// .getExternalCacheDir().getAbsolutePath() : context
	// .getCacheDir().getAbsolutePath();
	//
	// return new File(cachePath + File.separator + DISK_CACHE_SUBDIR);
	// }

	public static File getInternalCacheDirectory(Context context) {
		// Check if media is mounted or storage is built-in, if so, try and use
		// external cache dir
		// otherwise use internal cache dir
		final String cachePath = context.getCacheDir().getAbsolutePath();

		return new File(cachePath + File.separator + DISK_CACHE_SUBDIR);
	}

	public static File getTempDirectory(Context context) {
		final String cachePath = DeviceUtils.hasSDCard() ? context
				.getExternalFilesDir("").getAbsolutePath() : context
				.getFilesDir().getAbsolutePath();

		File file = new File(cachePath + File.separator + DISK_TEMP_SUBDIR);
		if (!file.exists()) {
			file.mkdirs();
		}

		return file;
	}

	public static String createTimeStamp() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HH_mm_ss",
				Locale.US);
		return sdf.format(Calendar.getInstance().getTime());
	}

	public static File getDirectory(Context context, String name) {
		final String cachePath = DeviceUtils.hasSDCard() ? context
				.getExternalFilesDir("").getAbsolutePath() : context
				.getFilesDir().getAbsolutePath();

		File file = new File(cachePath + File.separator + name);
		if (!file.exists()) {
			file.mkdirs();
		}

		return file;
	}

	public static File getExternalDirectory(Context context, String name) {
		boolean hasSDCard = DeviceUtils.hasSDCard();
		if (!hasSDCard) {
			return null;
		}
		// if (TextUtils.isEmpty(CONFIG.LOCAL.getStorage(context))) {
		// CONFIG.LOCAL.setStorage(context, hasSDCard ? EXTERNAL : INTERNAL);
		// }
		// final String cachePath = hasSDCard ? context.getExternalFilesDir("")
		// .getAbsolutePath() : context.getFilesDir().getAbsolutePath();

		File file = new File(Environment.getExternalStorageDirectory()
				.getAbsoluteFile() + File.separator + name);
		if (!file.exists()) {
			file.mkdirs();
		}

		return file;
	}

	// public static String getCurrentAppStorage() {
	// return DeviceUtil.hasSDCard() ? EXTERNAL : INTERNAL;
	// }

	public static boolean delete(File dir) {
		if (dir != null) {
			if (dir.isDirectory()) {
				String[] children = dir.list();
				if (children != null) {
					for (int i = 0; i < children.length; i++) {
						boolean success = delete(new File(dir, children[i]));
						if (!success) {
							return false;
						}
					}
				}
			}
			boolean delete = dir.delete();
			Logging.print("delete file "+ dir.getAbsolutePath()+" : " +delete);
			return delete;
		}
		return false;
	}
}
